package com.bjtang.fileSync.nio;

import java.io.IOException;
import java.nio.channels.SocketChannel;

import com.bjtang.fileSync.util.FileCODEC;
import com.bjtang.fileSync.util.FileConfig;
import java.net.InetSocketAddress;

/**
 * NIOClient 2024.1.12 @bjtang
 */
public class NIOClient {
	private String ip;
	private Integer port;

	private FileService fileService;

	public NIOClient(String ip, Integer port) {
		this.ip = ip;
		this.port = port;
		fileService = new FileService();
	}

	public NIOClient() {
		ip = FileConfig.readConfig("ip").trim();
		port = Integer.valueOf(FileConfig.readConfig("port").trim());
		fileService = new FileService();
	}

	/*
	 * 上传文件至服务器 //服务器接受
	 */
	public void fileDownload(SocketDto socketDto) throws IOException {

		socketDto.setFileMethod("fileDownload");
		SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress(ip, port));
		byte[] encoder = FileCODEC.encoder(socketDto);

		FileCODEC.writeChannel(socketChannel, encoder);
		// 客户端服务器发送和接受是相反的!!!
		fileService.fileUpload(socketChannel, socketDto);
	}

	/*
	 * 下载文件至服务器 //服务器发送
	 */
	public void fileUpload(SocketDto socketDto) throws IOException {
		socketDto.setFileMethod("fileUpload");
		// TODO 应该保持连接状态，使用线程池进行线程复用
		SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress(ip, port));
		// 客户端服务器发送和接受是相反的!!!
		fileService.fileDownload(socketChannel, socketDto);

	}

	public void fileRemove(SocketDto socketDto) throws IOException {
		socketDto.setFileMethod("fileRemove");
		// TODO 应该保持连接状态，使用线程池进行线程复用
		SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress(ip, port));
		byte[] encoder = FileCODEC.encoder(socketDto);
		FileCODEC.writeChannel(socketChannel, encoder);
//		fileService.fileRemove(socketChannel, socketDto);
		System.err.println("fileRemove " + new String(FileCODEC.readChannel(socketChannel)));
	}

}
